import EventBus from "@/utils";
import { reactive, watch, ref, Ref, toRefs, unref } from "vue";

type IQRef<T> = { [P in keyof T]?: Ref<T[P]> | T[P] };
export function useTable<
  R extends { list: any; total: number },
  P extends object,
  S
>(reqApi: (params: P) => RpI<R>, queryParams?: IQRef<P>) {
  let list = ref<R["list"]>([]);
  let params = {} as P;

  watch(
    () => queryParams,
    (val, oldval) => {
      for (let key in val) {
        if (val[key] !== undefined) {
          params[key] = unref(val[key]) as P[Extract<keyof P, string>]; // p[keyword] | p[pageSize] | p[pageNum]
        }
      }
    },
    { deep: true, immediate: true }
  );

  // 分页数据
  let paginate = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  // 返回数据
  let paginateData = reactive({
    total: 0,
  });

  // 请求列表数据
  async function getData() {
    // console.log(2222);
    let roleListRes = await reqApi({
      pageNum: paginate.pageNum,
      pageSize: paginate.pageSize,
      ...params,
    });
    if (roleListRes.code === 200) {
      list.value = roleListRes.data.list;
      paginateData.total = roleListRes.data.total;
    }
  }
  getData();

  EventBus.on("search", (val: string) => {
    params = { keyword: val } as any;
    getData();
  });

  // 切换启用
  function switchfn(params: number) {
    // console.log(params);
  }
  // 分页
  function handleSizeChange(val: number) {
    console.log(val);

    getData();
  }
  function handleCurrentChange(val: number) {
    paginate.pageNum = val;
    getData();
  }
  // 搜索
  function searchfn() {
    getData();
  }
  EventBus.on("isEdit", () => {
    getData();
  });

  return {
    list,
    paginate,
    switchfn,
    handleSizeChange,
    handleCurrentChange,
    searchfn,
    getData,
    paginateData,
  };
}
